﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Commerce.Base.Presentation
{
    public class RequestModule : IHttpModule
    {
        public struct RequestVariables
        {
            public static string OriginalUrl
            {
                get { return System.Web.HttpContext.Current.Items[ORIGINAL_URL].ToString(); }
            }

            public static string PageID
            {
                get { return System.Web.HttpContext.Current.Items[PAGE_ID].ToString(); }
            }
        }
        
        private HttpApplication application;

        public const string ORIGINAL_URL = "OriginalRequestUrl";
        public const string PAGE_ID = "PageId";

        #region IHttpModule Members
        public void Dispose()
        { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Application_BeginRequest);
            context.PostAuthenticateRequest += new EventHandler(Application_PostAuthorizeRequest);
            this.application = context;
        }
        #endregion

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            HttpContext httpContext = this.application.Context;
            httpContext.Items[ORIGINAL_URL] = application.Context.Request.Url.PathAndQuery;
        }

        protected void Application_PostAuthorizeRequest(object sender, EventArgs e)
        {
            RewritePath(this.application);
        }

        protected void RewritePath(HttpApplication application)
        {
            HttpContext context = application.Context;
            string path = context.Request.Path.ToLower();
            if (path.IndexOf(".aspx") > -1 || path.IndexOf('.') == -1)
            {
                string query = context.Request.Url.Query;
                if (query.Length > 1)
                    query = query.Substring(1);
                context.Items[PAGE_ID] = path;
                context.RewritePath(string.Format("~/default.aspx?{0}", query));
            }
        }
    }
}
